package com.mxy.myapplication2.kotlin

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.mxy.myapplication2.R
import com.mxy.myapplication2.java.Util
import com.mxy.myapplication2.service.SocketClient
import kotlinx.android.synthetic.main.activity_socket_client.*

/**
 * 基于TCP的Socket通信_client端
 */
class SocketClientActivity : AppCompatActivity(), View.OnClickListener {


    //以后台服务的形式启动socket
    private val clientIntent: Intent by lazy {
        Intent(this, SocketClient::class.java)
    }
    //记录服务器状态值以及客户端发送过来的消息
    private val informations: ArrayList<String> = ArrayList()
    private lateinit var adapter: AdapterForSocketServerInformationList
    private val newContentReceiver: NewContentReceiver = NewContentReceiver()
    private val linearLayoutManager by lazy {
        LinearLayoutManager(this)
    }

    companion object {
        private val clientClassName = "com.mxy.myapplication2.service.SocketClient"
        val newContentReceiverAction = "newMessageClient"
        val sendMessageAction = "sendMessageAction"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_socket_client)
        initView()


        val intentFilter = IntentFilter()
        intentFilter.addAction(newContentReceiverAction)
        registerReceiver(newContentReceiver, intentFilter)
    }

    fun initView() {
        findViewById<View>(R.id.sendMessage).setOnClickListener(this)
        findViewById<View>(R.id.connectSocketServer).setOnClickListener(this)
        findViewById<View>(R.id.disconnectSocketServer).setOnClickListener(this)

        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        this.messageList.layoutManager = linearLayoutManager
        adapter = AdapterForSocketServerInformationList(this, informations)
        this.messageList.adapter = adapter
    }

    /**
     * 连接服务器
     * */
    fun connectSocketServer() {
        if (Util.isServiceExisted(this, clientClassName)) {
            Util.showToast(this, "Client已启动")
        } else {
            startService(clientIntent)
            addNewInformation("启动Client")
        }
    }

    /**
     * 发送消息
     * */
    fun sendMessage() {

        if (!Util.isServiceExisted(this, clientClassName)) {
            Util.showToast(this, "Client未启动")
        } else if (message.text.toString().trim().equals("")) {
            Util.showToast(this, "请输入有效内容")
            return
        } else {
            val sendMessage = message.text.toString().trim()
            val intent = Intent(sendMessageAction)
            intent.putExtra(sendMessageAction, sendMessage)
            sendBroadcast(intent)
            addNewInformation("消息已发送 : " + sendMessage)
            message.setText("")
        }

    }

    /**
     * 断开与服务器连接
     * */
    fun disconnectSocketServer() {
        if (!Util.isServiceExisted(this, clientClassName)) {
            Util.showToast(this, "Client已关闭")
        } else {
            stopService(clientIntent)
            addNewInformation("手动关闭Client")
        }
    }

    /**
     * 记录操作日志和从客户端发来的消息并刷新列表
     * */
    fun addNewInformation(content: String) {

        if (!"".equals(content)) {
            informations.add(content)
            adapter.notifyDataSetChanged()
            linearLayoutManager.scrollToPosition(informations.size - 1)
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.connectSocketServer -> {
                connectSocketServer()
            }
            R.id.sendMessage -> {
                sendMessage()
            }
            R.id.disconnectSocketServer -> {
                disconnectSocketServer()
            }
        }
    }


    inner class NewContentReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null && intent.action != null) {
                if (newContentReceiverAction.equals(intent.action)) {
                    if (intent.getStringExtra(newContentReceiverAction) != null) {
                        addNewInformation(intent.getStringExtra(newContentReceiverAction))
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService(clientIntent)
        unregisterReceiver(newContentReceiver)
    }
}